//
//  MQRequestTools.m
//  meiquan
//
//  Created by hejingjin on 2017/10/29.
//  Copyright © 2017年 mq. All rights reserved.
//

#import "MQRequestTools.h"

#import "MQBaseUserInfoModel.h"

@implementation MQRequestTools
// 懒加载
- (AFHTTPSessionManager *)sessionManager {
    
    if (!_sessionManager) {
        _sessionManager = [AFHTTPSessionManager manager];
        
    }
    return _sessionManager;
}

-(AFNetworkReachabilityManager *)reachabilityManager{
    
    if (!_reachabilityManager) {
        _reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    }
    return _reachabilityManager;
}

-(AFNetworkReachabilityStatus)getnetworkState{
    
    __block    NSInteger outstatus = _reachabilityManager.networkReachabilityStatus;
    [_reachabilityManager startMonitoring];
    return outstatus;
}

#pragma mark - sharedInstance
+ (instancetype)sharedInstance {
    
    static MQRequestTools * sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sharedInstance = [[MQRequestTools alloc] init];
    });
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
//    if ([userinfo.userId isEqualToString:@""]|| !userinfo.userId) {
//    
//    }else{
//  
//    }

    return sharedInstance;
}

- (instancetype)init {
    
    self = [super init];
    if (self) {
        
        _reachabilityManager = [AFNetworkReachabilityManager sharedManager];
        
        //配置网络请求属性
        _sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/plain", @"application/json", @"text/javascript",@"multipart/form-data", nil];
        
        
        _sessionManager.requestSerializer.timeoutInterval = 20.0;
        
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        
//        [_sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        //设置token
        
    }
    return self;
}

//get请求
+(void)GETWithMethod:(NSString *)method params:(NSDictionary *)params success:(BRTCRequestSuccess)success failure:(BRTCRequestFailure)failure{
    
    MQRequestTools *requestools = [MQRequestTools sharedInstance];
    
    
    NSString *requesturl = [requestools serverUrlWithMethods:method];
    NSString *paramstr = @"";
    if (params) {
        
        
        NSArray *keyarray = [params allKeys];
        //        [keyarray sortUsingComparator: ^NSComparisonResult (NSString *str1, NSString *str2) {
        //            return [str1 compare:str2];
        //        }];
        NSArray *key = [NSArray array];
        key =  [keyarray sortedArrayUsingComparator:^NSComparisonResult (NSString *str1, NSString *str2) {
            return [str1 compare:str2];
        }];
        
        //        NSArray *values = [params allValues];
        for (NSString *str in key) {
            paramstr = [paramstr stringByAppendingString:[params valueForKey:str]];
        }
    }
    
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    if ([userinfo.userId isEqualToString:@""] || !userinfo.userId) {
        
    }else{
        
        NSString *sign = [MQHmacUtils hmac:paramstr withKey:userinfo.token];
        [requestools.sessionManager.requestSerializer setValue:userinfo.userId forHTTPHeaderField:@"userId"];
        [requestools.sessionManager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
    }

    
    //加密方式
    
    [requestools.sessionManager GET:requesturl parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([[responseObject valueForKey:@"code"] integerValue] == 0) {
            !success ? : success(responseObject);
        }else{
            !failure ? : failure(responseObject);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        !failure ? : failure(error);
        
    }];
}

//get请求
+(void)GETUPWithMethods:(NSString *)method params:(NSDictionary *)params success:(BRTCRequestSuccess)success failure:(BRTCRequestFailure)failure{
    
    MQRequestTools *requestools = [MQRequestTools sharedInstance];
    
    
    NSString *requesturl = method;
    NSString *paramstr = @"";
    if (params) {
        
        
        NSArray *keyarray = [params allKeys];
        //        [keyarray sortUsingComparator: ^NSComparisonResult (NSString *str1, NSString *str2) {
        //            return [str1 compare:str2];
        //        }];
        NSArray *key = [NSArray array];
        key =  [keyarray sortedArrayUsingComparator:^NSComparisonResult (NSString *str1, NSString *str2) {
            return [str1 compare:str2];
        }];
        
        //        NSArray *values = [params allValues];
        for (NSString *str in key) {
            paramstr = [paramstr stringByAppendingString:[params valueForKey:str]];
        }
    }
    
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    if ([userinfo.userId isEqualToString:@""] || !userinfo.userId) {
        
    }else{
        
        NSString *sign = [MQHmacUtils hmac:paramstr withKey:userinfo.token];
//        [requestools.sessionManager.requestSerializer setValue:userinfo.userId forHTTPHeaderField:@"userId"];
//        [requestools.sessionManager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
    }
    
    
    //加密方式
    
    [requestools.sessionManager POST:requesturl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([[responseObject valueForKey:@"code"] integerValue] == 0) {
            !success ? : success(responseObject);
        }else{
            !failure ? : failure(responseObject);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        !failure ? : failure(error);
        
    }];
}

//post请求
+(void)POSTWithMethod:(NSString *)method params:(NSDictionary *)params success:(BRTCRequestSuccess)success failure:(BRTCRequestFailure)failure{
    
    
    MQRequestTools *requestools = [MQRequestTools sharedInstance];
    NSString *requesturl = [requestools serverUrlWithMethods:method];
    
    
    
    NSString *paramstr = @"";
    if (params) {
        
        
        NSArray *keyarray = [params allKeys];
//        [keyarray sortUsingComparator: ^NSComparisonResult (NSString *str1, NSString *str2) {
//            return [str1 compare:str2];
//        }];
        NSArray *key = [NSArray array];
        key =  [keyarray sortedArrayUsingComparator:^NSComparisonResult (NSString *str1, NSString *str2) {
                return [str1 compare:str2];
        }];
        
//        NSArray *values = [params allValues];
        for (NSString *str in key) {
         paramstr = [paramstr stringByAppendingString:[params valueForKey:str]];
        }
    }
    
    
    
    

    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    if ([userinfo.userId isEqualToString:@""] || !userinfo.userId) {
        
    }else{
        
        NSString *sign = [MQHmacUtils hmac:paramstr withKey:userinfo.token];
         [requestools.sessionManager.requestSerializer setValue:userinfo.userId forHTTPHeaderField:@"userId"];
        [requestools.sessionManager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
        NSLog(@"%@",sign);
    }
    
    
    [requestools.sessionManager POST:requesturl parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([[responseObject valueForKey:@"code"] integerValue] == 0) {
            !success ? : success(responseObject);
        }else{
            !failure ? : failure(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        !failure ? : failure(error);
        NSLog(@"%@",error);
        
    }];
}

// 在对象销毁时，取消已经在队列中的请求
- (void)dealloc {
    
    [self.sessionManager invalidateSessionCancelingTasks:YES];
    
}

#pragma mark - serverUrl
- (NSString *)serverUrlWithMethods:(NSString*)methdos{
    
    NSString *baseUrl = MainInterfaceUrl;
    return [NSString stringWithFormat:@"%@%@", baseUrl, methdos];
    
    
}
@end
